from django.shortcuts import render

# Create your views here.
from utils.views import LoginRequiredJSONMixin
from libs.qiniuyun.upload_file import storage
from utils.real_name_authentication import Authentication
from django.http import JsonResponse
from apps.users.models import User
from django.conf import settings
from django.views import View
import json
import re


class CenterListView(LoginRequiredJSONMixin, View):
    """个人中心列表展示"""

    def get(self, request):
        # 1. 获取当前登录用户
        user = request.user

        if user.avatar:
            avatar_url = user.avatar.url

        else:
            avatar_url =''

        # 2. 拼接数据
        data = {
            "avatar_url": avatar_url,
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }

        return JsonResponse({
            "errmsg": "OK",
            "errno": "0",
            "data": data})


class UserNameView(LoginRequiredJSONMixin, View):
    """修改用户名"""

    def put(self, request):
        # 1. 接收数据
        json_data = json.loads(request.body.decode())
        # 2. 提取参数
        username = json_data.get('name')
        # 3. 验证参数 匹配非特殊字符
        if not re.match('\w+', username):
            return JsonResponse({'errno': 400, 'errmsg': '名字不合法!'})

        count = User.objects.filter(username=username).count()  # 判断是否存在
        if count:
            return JsonResponse({'errno': 400, 'errmsg': '用户名太受欢迎了,请更换一个'})

        # 4. 更新参数
        user = request.user
        user.username = username
        # 5. 保存用户名
        user.save()

        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"
        })


class AvatarView(LoginRequiredJSONMixin, View):
    """上传头像"""

    def post(self, request):
        # 1.提取参数
        file = request.FILES.get('avatar')

        if file is None:
            return JsonResponse({'errno': 400, 'errmsg': '没有上传图片'})

        data = file.read()

        if data is None:
            return JsonResponse({'errno': 400, 'errmsg': '没有上传图片'})

        avatar_name = storage(data)

        # 上传失败avatar_name为空
        if avatar_name is None:
            return JsonResponse({"errno":400,
                                 'errsmg':'上传失败'})

        # 2. 保存数据
        user = request.user
        user.avatar = avatar_name
        user.save()

        # 3. 拼接数据
        # avatar_url = settings.QN_BASE_URL + avatar_name

        # 4. 返回响应对象
        return JsonResponse({
            "data": {
                "avatar_url": user.avatar.url
            },
            "errno": 0,
            "errmsg": "认证信息保存成功"
        })


class RealNameVerificationView(LoginRequiredJSONMixin, View):
    """实名验证"""

    def post(self, request):

        # 1. 接收数据
        user = request.user
        json_data = json.loads(request.body.decode())

        # 2. 提取数据
        real_name = json_data.get("real_name")
        id_card = json_data.get("id_card")

        # 3. 验证数据 字段不能为空
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 400, 'errmsg': '字段不能为空'})

        if not re.match('^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$', real_name):
            return JsonResponse({'errno': 400, 'errmsg': '姓名不合法'})

        if not re.match(
                '^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                id_card):
            return JsonResponse({'errno': 400, 'errmsg': '身份证格式不正确'})

        # 身份证不能重复注册
        idcard = User.objects.filter(id_card=id_card).count()
        if idcard:
            return JsonResponse({'errno': 400, 'errmsg': '当前身份证已注册'})

        # 阿里云实名认证
        content = Authentication().real_name_authentication(id_card, real_name)
        dict_content = json.loads(content)

        if content is None or dict_content['respCode'] != '0000':
            return JsonResponse({'errno': 400, 'errmsg': '实名失败'})

        # 4. 写入数据
        try:

            user.real_name = real_name
            user.id_card = id_card
            user.save()

        except Exception:
            return JsonResponse({'errno': 400, 'errmsg': '保存失败'})

        # 数据加密
        real_name = user.real_name
        id_card = user.id_card

        new_name = real_name[:1:] + '*' * len(real_name[1:])
        new_idcard = id_card[:6] + '*' * 8 + id_card[14:]

        data = {
            'real_name': new_name,
            'id_card': new_idcard,
        }

        # 5. 返回响应
        return JsonResponse({
            "errno": "0",
            "errmsg": "认证信息保存成功",
            "data": data
        })

    def get(self, request):
        # 以get方式获取实名认证信息

        # 1. 接收参数
        user = request.user

        # 2. 提取数据
        real_name = user.real_name
        id_card = user.id_card

        # 数据加密
        new_name = real_name[:1:] + '*'* len(real_name[1:])
        new_idcard = id_card[:6] + '*' * 8 + id_card[14:]

        data = {
            'real_name': new_name,
            'id_card': new_idcard,
        }

        # 3. 返回响应
        return JsonResponse({
            'errno': 0,
            'data': data,
            'errmsg': '成功'
        })
